<?php
declare (strict_types=1);

namespace app\middleware;

use think\Exception;

class Auth
{
    /**
     * 验证 Token 和 角色
     *
     * @param \think\Request $request
     * @param \Closure $next
     * @return Response
     * @throws Exception
     */
    public function handle($request, \Closure $next)
    {
        //token 验证
        $filtrationUrl = ['/index.php/login', '/index.php/register','/index.php/captcha'];
        $url = $request->url();
        if (!in_array($url, $filtrationUrl)) {
            $token = $request->header('token');
            if ($token === null) {
                throw new Exception('token未找到', 500);
            }

            $result = checkToken($token);
            if ($result['code'] !== 200) {
                return json(['msg' => $result['msg'],'code'=> $result['code']],403);
            }

            $request -> uid =  $result['data'] -> uid;

        }
        return $next($request);
    }
}
